<?php

class SCFunction {
	
	/**
	 * 
	 * 显示友好时间
	 * < 1分钟 xx秒以前
	 * < 1小时 xx分钟以前
	 * < 1天     xx小时以前
	 * 1 < 2天  昨天 HH:ii:ss
	 * 2 < 3天  前天  HH:ii:ss
	 * else   yy-mm-dd HH:ii:ss
	 */
	public static function friendlyTime($time) {
		$time = strtotime($time);
		$now = time();
		$sub = $now - $time;
		$subDay = $sub / 3600 / 24;
		if ($sub < 60) {
			return ($sub ? $sub : '1').'秒前';
		} elseif ($sub >= 60 && $sub < 3600) {
			return floor($sub/60).'分钟前';
		} elseif ($sub >= 3600 && $subDay == 0) {
			return floor($sub/3600).'小时前';
		} elseif ($subDay == 1) {
			return '昨天'.date('H:i', $time);
		} elseif ($subDay == 2) {
			return '前天'.date('H:i', $time);
		} elseif (date('Y', $now) == date('Y', $time)) {
			return date('m月d日 H:i', $time);
		} else {
			return date('Y年m月d日 H:i', $time);
		}
	}
	
	public static function directoryCreate($dir, $mode = 0777) {
		if ((file_exists($dir) && is_dir($dir)) || @mkdir($dir,$mode)) return true;
		if (!self::directoryCreate(dirname($dir),$mode)) return false;
		return @mkdir($dir,$mode);
	}
	
	public static function getFileExtension($path) {
		return substr($path, strrpos($path, '.') + 1);
	}
	
	/**
	 * 
	 * 复制目录到另一个目录
	 * @param string $srcdir 源目录
	 * @param string $dstdir 目标目录
	 */
	public static function directoryCopy($srcdir, $dstdir){
		if(!is_dir($dstdir)) {
			$nowdir='';
			$dstdirarray=explode(SC_DS,$dstdir);
			foreach ($dstdirarray as $newdir) {
				$nowdir.=$newdir.SC_DS;
				if(!is_dir($nowdir)) @mkdir($nowdir);
			}
		}
		$dir = @opendir($srcdir);
		while (($file = readdir($dir)) !== false) {
			if($file=='.'||$file=='..') continue;
			if(is_dir($srcdir.SC_DS.$file)){
				self::directoryCopy($srcdir.SC_DS.$file,$dstdir.SC_DS.$file);
			} else {
				copy($srcdir.SC_DS.$file,$dstdir.SC_DS.$file);
			}
		}
		closedir($dir);
	}
	
	/**
	 * 
	 * 删除目录及目录下所有文件
	 * @param string $dir
	 */
	public static function directoryDelete($dir) {
	    $dh=opendir($dir);
	    while (true == ($file = readdir($dh))) {
	        if($file!="." && $file!="..") {
	            $fullpath=$dir.SC_DS.$file;
	            if(!is_dir($fullpath)) {
	                unlink($fullpath);
	            } else {
	                self::directoryDelete($fullpath);
	            }
	        }
	    }
	    closedir($dh);
	    if(rmdir($dir)) {
	        return true;
	    } else {
	        return false;
	    }
	}
	
	/**
	 * 
	 * 判断文件是否为合法图片
	 * @param string $filename 文件完整路径
	 */
	public static function isImage($filename){
	    $types = '.gif|.jpeg|.jpg|.png|.bmp';//定义检查的图片类型
	    if(file_exists($filename)){
	        $info = getimagesize($filename);
	        $ext = image_type_to_extension($info['2']);
	        return stripos($types,$ext);
	    }else{
	        return false;
	    }
	}
	
	/**
	 * 
	 * 字符串截取
	 * @param unknown_type $str
	 * @param unknown_type $start
	 * @param unknown_type $length
	 * @param unknown_type $charset
	 * @param unknown_type $suffix
	 */
	public static function stringCut($str, $start=0, $length, $charset="utf-8", $suffix=true) {
		if(strlen($str) <= $length) return $str;
	    if(function_exists("mb_substr"))
	        return mb_substr($str, $start, $length, $charset).($suffix ? '...' : '');
	    elseif(function_exists('iconv_substr')) {
	        return iconv_substr($str,$start,$length,$charset).($suffix ? '...' : '');
	    }
	    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	    preg_match_all($re[$charset], $str, $match);
	    $slice = join("",array_slice($match[0], $start, $length));
	    if($suffix) return $slice."…";
	    return $slice;
	}
	
	/**
	 * 
	 * 拼接成完整的url
	 */
	public static function fullUrl($url) {
		return scURL().'/'.trim($url, '/');
	}
	
	/**
	 * 
	 * 生成短URL
	 * @param string $url
	 */
	public static function shortUrl($url) {
		$base32 = array(
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
			'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
			'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
			'y', 'z', '0', '1', '2', '3', '4', '5'
		);
 
		$hex = md5(trim($url, '/'));
		$hexLen = strlen($hex);
		$subHexLen = $hexLen / 8;
		$output = array();
	 
		for($i = 0; $i < $subHexLen; $i++) {
			$subHex = substr ($hex, $i * 8, 8);
			$int = 0x3FFFFFFF & (1 * ('0x'.$subHex));
			$out = '';
			for ($j = 0; $j < 6; $j++) {
				$val = 0x0000001F & $int;
				$out .= $base32[$val];
				$int = $int >> 5;
			}
			$output[] = $out;
		}
		
		return $output[0];
    }
	
	/**
	 * 
	 * 返回当前连接的客户端IP
	 * @return string IP地址
	 */
	public static function getClientIP() {
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
			$ip = getenv('REMOTE_ADDR');
		}
		elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : 'unknown';
	}
	
	/**
	 * 模拟post请求并返回响应结果
	 * @param string $url
	 * @param string $data
	 * @return string
	 */
	public static function post($url, $data) {
		#echo '<Pre>';
		#print_r($data);die;
		$ch = curl_init(); // 需开启php_openssl.dll扩展
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_URL, $url);
		$ret = curl_exec($ch);
		
		curl_close($ch);
		return $ret;
	}
	
	/**
	 * 获取远程url内容
	 * @param string $url
	 * @return string
	 */
	public static function getUrlContents($url) {
		if (ini_get("allow_url_fopen") == "1")
			return file_get_contents($url);
		
		$ch = curl_init(); // 需开启php_openssl.dll扩展
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		$result =  curl_exec($ch);
		curl_close($ch);
	
		return $result;
	}
	
	/**
	 *
	 * 异步返回失败信息
	 * @param string $data 失败信息
	 */
	public static function ajaxFail($data = '') {
		die(json_encode(array('__status' => 'fail', 'data' => $data)));
	}
	
	/**
	 *
	 * 异步成功返回数据
	 * @param array $data
	 */
	public static function ajaxSuccess($data = '') {
		die(json_encode(array('__status' => 'ok', 'data' => $data)));
	}
}